package me.mononin.factory.preseneter.account;

import android.text.TextUtils;

import net.qiujuer.genius.kit.handler.Run;
import net.qiujuer.genius.kit.handler.runable.Action;

import me.mononin.common.factory.data.DataSource;
import me.mononin.common.factory.presenter.BasePresenter;
import me.mononin.factory.R;
import me.mononin.factory.data.helper.AccountHelper;
import me.mononin.factory.model.api.account.LoginModel;
import me.mononin.factory.model.db.User;
import me.mononin.factory.persistence.Account;

/**
 * @author Yaning
 * @description
 * @date 18-4-21 下午7:30
 */
public class LoginPresenter extends BasePresenter<LoginContract.View>
        implements LoginContract.presenter,DataSource.Callback<User>{

    public LoginPresenter(LoginContract.View view) {
        super(view);
    }

    @Override
    public void login(String account, String password) {
        start();
        LoginContract.View view = getView();
        if (TextUtils.isEmpty(account)
                ||TextUtils.isEmpty(password)){
            view.showError(R.string.data_account_login_invalid_parameter);
        }else {
            LoginModel model = new LoginModel(account,password, Account.getPushId());
            AccountHelper.login(model,this);
        }
    }

    @Override
    public void onDataLoaded(User user) {
        //获取当前视图
        final LoginContract.View view = getView();

        if (view==null){
            return;
        }

        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.loginSuccess();
            }
        });
    }

    @Override
    public void onDataNotAvailable(final int res) {
        //获取当前视图
        final LoginContract.View view = getView();

        if (view==null){
            return;
        }

        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                view.showError(res);
            }
        });
    }
}
